﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using APMS.WebSite.Common;
using APMS.WebSite.Models.DataStore;
using APMS.WebSite.Models.ViewData;
using APMS.WebSite.Models.ViewData.Pages;
using APMS.WebSite.Models.ViewData.UserControls;

namespace APMS.WebSite.Controllers
{
    /// <summary>
    /// ProjectController controls all Views related to project operation which are:
    /// * Index (/Project/)
    /// * List (/Project/List)
    /// * Create (/Project/Create)
    /// * Overview (/Project/Overview/)
    /// * MORE
    /// </summary>
    /// <version>$Revision$ $Date$</version>
    /// <history>
    /// <record>09/15/2008. raQuiam - Created this file</record>
    /// </history>
    [HandleError]
    public class ProjectController : BaseController
    {
        #region Keys for ViewData
        /// <summary>
        /// Use in method List
        /// </summary>
        public const string PROJECTS_FOR_USER = "ProjectsForUser";

        /// <summary>
        /// Use in method OverView
        /// </summary>
        //public const string CURRENT_PROJECT = "currentProject";
        public const string PROJECT_USER = "projectUser";

        public const string PROJECT_CALENDAR = "ProjectCalendar";
        #endregion

        /// <summary>
        /// Default action
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View("List");
        }

        #region List Action
        /// <summary>
        /// List all project that current user applicable
        /// </summary>
        /// <returns></returns>
        public ActionResult List()
        {
            // Initialize data required by master page
            ActionResult exception = base.InitializeAction();
            if (exception != null)
                return exception;

            // TODO: Move to ProjectService
            MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();
            string findUser = UserProfile.UserName;
            var query =
                from project in db.Project
                from projUser in db.ProjectUser
                from user in db.Users
                where
                    project.ProjectID == projUser.ProjectID &&
                    projUser.UserName == user.UserName &&
                    user.UserName == findUser
                select project;

            // Save information to View, Type is List<Project>
            base.SetTitle("Project Listing");
            ViewData[PROJECTS_FOR_USER] = query.ToList();

            return View("List");
        }
        #endregion

        #region Overview Action
        /// <summary>
        /// Display the Project Dashboard for given projectId
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public ActionResult Overview(int id)
        {
            // Initialize data required by master page
            ActionResult exception = base.InitializeAction(MainNavItemType.Overview);
            if (exception != null)
                return exception;

            // TODO: Move to ProjectService
            MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();
            var query =
                from project in db.Project
                where project.ProjectID == id
                select project;

            ManageProjectViewData viewData = null;
            if (query.Count() > 0)
            {
                // Prepare ViewData
                viewData = new ManageProjectViewData();
                viewData.CurrentProject = query.First();

                // Set current project, so MainNav and other UserControls would know
                base.SetInfoToUserControls(viewData.CurrentProject);

                #region Find all events

                var queryMessages =
                    from message in db.Message
                    where
                        message.ProjectID == id
                    //group message by message.AddDate into g1
                    //select g1;
                    orderby message.AddDate descending
                    select message;

                var queryTodos =
                    from todo in db.ToDo
                    where
                        todo.ProjectID == id
                    orderby todo.AddDate descending
                    select todo;


                List<EventItem> allEvents = new List<EventItem>();
                EventItem cEvent = null;

                List<Message> msgEvents = queryMessages.ToList();
                foreach (Message msg in msgEvents)
                {
                    cEvent = new EventItem();
                    cEvent.Type = EventType.Message;
                    cEvent.Location = msg.MessageTopic;
                    cEvent.Summary = msg.MessageDetail;
                    cEvent.AssignedTo = msg.UserName;

                    allEvents.Add(cEvent);
                }

                List<ToDo> todoEvents = queryTodos.ToList();
                foreach (ToDo todo in todoEvents)
                {
                    cEvent = new EventItem();
                    cEvent.Type = EventType.ToDo;
                    cEvent.Location = todo.ToDoName;
                    cEvent.Summary = todo.ToDoName;
                    cEvent.AssignedTo = todo.UserName;

                    allEvents.Add(cEvent);
                }

                viewData.EventItems = allEvents;
                #endregion

                // ViewData for ProjectCalendar UserControl
                ProjectCalendarViewData projectCalendarModel = new ProjectCalendarViewData();
                // TODO: Calculate data here
                ViewData[PROJECT_CALENDAR] = projectCalendarModel;


                // Set Window Title
                base.SetTitle(viewData.CurrentProject.ProjectName);
            }
            else
            {
                throw new ArgumentException("No projectID specify");
            }

            return View("Overview", viewData);
        }
        #endregion

        #region Create Action
        /// <summary>
        /// Create new Project
        /// </summary>
        /// <returns></returns>
        public ActionResult Create()
        {
            // Initialize data required by master page
            ActionResult exception = base.InitializeAction();
            if (exception != null)
                return exception;

            // Set Window Title
            base.SetTitle("Create New Project");

            // Prepare ViewData
            ManageProjectViewData viewData = new ManageProjectViewData();

            // If POST means UPDATE the value from Request.Form to DB
            // If GET means VIEW the value from DB
            if (Request.HttpMethod == Constants.HttpMethod.POST)
            {
                #region Create new record in DB

                #region Extract values from Form
                string projectName = Request.Form["projectName"];
                string logo = Request.Form["logo"];
                #endregion

                // Prepare to INSERT by Linq
                MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();

                // Check existent of the project
                var query =
                    from project in db.Project
                    where
                        project.ProjectName == projectName
                    select project;
                
                // OK, not duplicate
                if (query.Count() <= 0)
                {
                    // new project
                    Project newProject = new Project();
                    newProject.Logo = logo;
                    newProject.ProjectName = projectName;
                    newProject.AddDate = DateTime.Now;
                    newProject.ModifyDate = DateTime.Now;

                    db.Project.InsertOnSubmit(newProject);
                    db.SubmitChanges(); // submit to get actual ProjectID

                    // new projectUser
                    ProjectUser newProjectUser = new ProjectUser();
                    newProjectUser.ProjectID = newProject.ProjectID;
                    newProjectUser.JoinDate = DateTime.Now;
                    newProjectUser.UserName = UserProfile.UserName; // assign to user who create new project

                    db.ProjectUser.InsertOnSubmit(newProjectUser);
                    db.SubmitChanges();

                    viewData.CurrentProject = newProject;
                    viewData.IsCurrentProjectUpdate = true;

                    // Redirect to  Project Overview
                    return RedirectToAction("Overview", new { id = newProject.ProjectID });
                }
                else
                {
                    ViewData[KEY_ERROR_MSG] = "Duplicate project name";
                }

                #endregion
            }
            else
            {
                viewData.IsCurrentProjectUpdate = false;
            }

            return View("Create", viewData);
        }
        #endregion

        public ActionResult Listuser(int projectId)
        {
            MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();
            //int.Parse(projectId)
            var query =
                from project in db.Project
                from projUser in db.ProjectUser
                from user in db.Users
                where
                    project.ProjectID == projUser.ProjectID &&
                    projUser.UserName == user.UserName &&
                    project.ProjectID == projectId
                select user;
            ViewData[PROJECT_USER] = query.ToList();

            ViewData["justwanttopreviewmassage"] = "";
            foreach (Users user in ViewData[PROJECT_USER] as List<Users>)
            {
                ViewData["justwanttopreviewmassage"] += user.ToString() + "<BR>";
            }
            return View("mytest");
        }   

        [Obsolete("Use ProjectController.Create() instead")]
        public ActionResult Add(String project_name, String logo)
        {
            MySQLDataStore db = DataStoreFactory.GetMySQLDataStore();
            //throw new NotImplementedException();   
            var query =
                from project in db.Project
                where
                    project.ProjectName == project_name
                select project;

            if (query.Count() <= 0)
            {
                // new project
                Project newProject = new Project();
                newProject.Logo = logo;
                newProject.ProjectName = project_name;
                newProject.AddDate = DateTime.Now;
                newProject.ModifyDate = DateTime.Now;
                // for testing
                newProject.Logo = Request.QueryString["logo"];
                newProject.ProjectName = Request.QueryString["project_name"];

                db.Project.Add(newProject);
                db.SubmitChanges();
                /////////////////////////////////////////////////////////////
                // new projectUser
                ProjectUser newProjectUser = new ProjectUser();
                newProjectUser.ProjectID = newProject.ProjectID;
                newProjectUser.JoinDate = DateTime.Now;
                newProjectUser.UserName = "admin";
                
                db.ProjectUser.Add(newProjectUser);
                db.SubmitChanges();

                //ViewData["justwanttopreviewmassage"] = newProject.ToString() + newProjectUser.ToString();
            }
            else {
                //ViewData["justwanttopreviewmassage"] = "No data";
            }
            return List();
        }


    }
}
